package com.enjoy.jvm.hotspot.src.share.vm.intepreter;

import com.enjoy.jvm.hotspot.src.share.tools.DataTranslate;
import com.enjoy.jvm.hotspot.src.share.tools.Stream;
import com.enjoy.jvm.hotspot.src.share.vm.memory.StackObj;
import com.enjoy.jvm.hotspot.src.share.vm.oops.CodeAttributeInfo;
import com.enjoy.jvm.hotspot.src.share.vm.oops.MethodInfo;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
public class BaseBytecodeStream extends StackObj {
    protected MethodInfo belongMethod;
    protected CodeAttributeInfo belongCode;

    protected int length;
    protected int index;
    protected byte[] codes;

    public int getU1Code() {
        if (index < 0 || index >= length) {
            throw new Error("字节码指令的索引超过了最大值");
        }
        return Byte.toUnsignedInt(codes[index++]);
    }

    public short getUnsignedShort() {
        if (index < 0 || index >= length) {
            throw new Error("字节码指令的索引超过了最大值");
        }
        byte[] u2Arr = new byte[2];
        Stream.readU2Simple(codes, index, u2Arr);
        index += 2;
        return (short) DataTranslate.byteToUnsignedShort(u2Arr);
    }

    public boolean end() {
        return index >= length;
    }
}
